const router = require('koa-router')()
const db = require('../utils/mysql.js');
const config  = require('../../config')[process.env.NODE_ENV];
router.get('/microtime',async ctx=>{
  const time = new Date().getTime()/1000
  // const time = new Date().toLocaleString()
  ctx.body=time
})
router.get('/getConfig',async ctx=> {
  // ctx.log(JSON.stringify(ctx))
  const field =ctx.query.field;
    if(!field){
      ctx.body={'err':1,'msg':'No filed'}
      return 
    }
    const value = await getConfig(field)
    ctx.body={'err':0,'value':value}
});
router.post('/add',async ctx=> {
	// 新增用户
  const data = ctx.request.body;
  var title = data.title;
  if(!title){
    ctx.body={'err':1,'msg':'标题不能为空'}

     return ;
  }
  var user = JSON.parse(ctx.cookies.get('user')||'{}');
  if(!user || !user.id){
    ctx.body={'err':2,'msg':'请登录','to':'/user/login'}
    return ;
  }
  var sql = "insert into blog_publish(title,content,create_id) values (:title,:content,:createId)";
  const result = await db.query(sql,{title:title,content:data.content,createId:user.id});
  if(result.insertId){
    ctx.body={'err':0}
  }
});
router.get('/', ctx=> {
  ctx.body='respond with a publish';
});

async function blogList(blog={}){
  let sql = "select a.id,a.title,a.content,a.create_id userId,a.create_time createTime,b.show_name userName from blog_publish a left join blog_user b on a.create_id=b.id where 1=1";
  const queryObj = {};
  if(blog.createId){
    sql += " and a.create_id=:createId";
    queryObj.createId = blog.createId;
  }
  return await db.query(sql+" order by a.create_id desc",queryObj);
}
async function getConfig(field){
  let sql = "select code,name ,str_value from bxc_fields where code =:code and name=:field";
  const result = await db.query(sql,{code:config.tt,field:field});
  if(result.length>0){
    return result[0]['str_value']
  }
  return ''
}

module.exports = router;
